﻿using System;
using log4net;
using log4net.Appender;
using Dala.Logger.BusinessEntities;
using Dala.Logger.BusinessLogicLayer;
using Dala.Logger.DataAccessLayer;
using Dala.Logger.Entity;

namespace Dala.Logger.Implementation
{
    public class CustomEFAppender : AppenderSkeleton
    {
        public string ConnectionString
        {
            get;
            set;
        }

        protected override void Append(log4net.Core.LoggingEvent loggingEvent)
        {
            var logServiceInformation = (LogServiceInformation)GlobalContext.Properties["LogServiceInformation"];
            if (logServiceInformation != null)
            {
                try
                {
                    var logError = new LogError
                    {
                        ProjectId = logServiceInformation.ProjectId,
                        TaskListId = logServiceInformation.TaskListId,
                        Type = loggingEvent.Level.Name,
                        Message = loggingEvent.MessageObject == null ? null : Convert.ToString(loggingEvent.MessageObject),
                        OtherInfo = logServiceInformation.OtherInfo == null ? null : Convert.ToString(logServiceInformation.OtherInfo),
                        DateCreated = Convert.ToDateTime(DateTime.Now),
                        StackTrace = logServiceInformation.StackTrace,
                        Exception =
                            logServiceInformation.Exception == null
                                ? logServiceInformation.Message
                                : "Source: " + (logServiceInformation.Exception.Source ?? "") +
                                  "; Message: " + (logServiceInformation.Exception.Message ?? "") +
                                  "; Stack: " + (logServiceInformation.Exception.StackTrace ?? ""),

                    };

                    var db = new LoggerEntities(ConnectionString);
                    new LogErrorBLL(db).CreateNewLogError(logError);

                    GlobalContext.Properties["LogServiceInformation"] = null;
                }
                catch (Exception ex)
                {
                    GlobalContext.Properties["OtherInfo"] = logServiceInformation.OtherInfo == null ? " " : Convert.ToString(logServiceInformation.OtherInfo);
                    LogManager.GetLogger("Dala.LoggerErrorLogger").Error(ex);
                    GlobalContext.Properties["LogServiceInformation"] = null;
                }
            }
        }
    }
}
